//
//  EasyRefresh.swift
//  Mall-swift
//
//  Created by dfpo on 2020/11/1.
//  Copyright © 2020 Bob. All rights reserved.
//

import Foundation
import MJRefresh
import HandyJSON
public protocol EasyTable: class {
    var m_table: UITableView { get }
    var m_datas: [HandyJSON] { get set }
}
public protocol EasyRefresh: EasyTable {
    var m_currentPage: Int { get set }
    func endRefresh()
    func loadDataAtPage(_ page: Int)
    func setupRefreshHeader()
    func setupRefreshFooter()
    func isFirstPage(resPageNum: Any) -> Bool
    func receivedDicts<T: HandyJSON>(_ dicts:[[String: Any]]?, atPage: Int, resPageNum: Any?, resPageSize: Any?,  objClass: T.Type)
}
extension EasyRefresh {
    public func endRefresh() {
        if let hd = m_table.mj_header, hd.isRefreshing {
            hd.endRefreshing()
            m_table.mj_footer?.endRefreshingWithNoMoreData()
        }
        m_table.mj_footer?.endRefreshing()
    }
    // MARK: - 上下拉刷新
    // MARK: 刷新控件
    public func setupRefreshHeader() {
        m_table.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.loadDataAtPage(1)
        })
        if m_table.mj_header == nil {
            loadDataAtPage(1)
        }
    }
    public func setupRefreshFooter() {
        m_table.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            self.loadDataAtPage(self.m_currentPage + 1)
        })
    }
    // MARK: - 数据处理
    public func isFirstPage(resPageNum: Any) -> Bool{
        if let pageInt = resPageNum as? Int, pageInt == 1 {
            return true
        }
        if let pageStr = resPageNum as? String, pageStr == "1" {
            return true
        }
        return false
    }
    /// 收到了数据
    /// - Parameters:
    ///   - dicts: 字典数组
    ///   - atPage: 获取的是哪一页，直接传loadDataAtPage的参数page
    ///   - resPageNum: 服务器返回的当前页数
    ///   - resPageSize: 服务器返回的一页加载多少个
    ///   - objClass: 要转换的模型
    public func receivedDicts<T: HandyJSON>(_ dicts:[[String: Any]]?, atPage: Int, resPageNum: Any?, resPageSize: Any?,  objClass: T.Type)  {
        let objs = [T].deserialize(from: dicts)?.compactMap{ $0 }
        if isFirstPage(resPageNum: resPageNum ?? 1) {
            m_datas.removeAll()
        }
        if let models = objs, models.count > 0 {
            m_currentPage = atPage
        }
        if let pageSizeInt = resPageSize as? Int , let resCount = objs?.count, pageSizeInt > resCount {
            m_table.mj_footer?.isHidden = true
        } else {
            m_table.mj_footer?.isHidden = false
        }
        if let models = objs {
            m_datas.append(contentsOf: models)
        }
        m_table.reloadData()
    }
}
